<?php
require(dirname(__FILE__).DIRECTORY_SEPARATOR.'facebook.php');

class FbLogin extends CInputWidget{
        
        public $devappid;
        public $devsecret;
        public $cookie = TRUE;
        public $domain;
        public $options = array();
        public $fname;
        public $lname;
        public $FB;
        public $Session;
        public $user;
        
        protected $userid;
        protected $username;
        
        
        
        public function run(){
         
        $controller = $this->controller;
        $this->controller->createAction('fblogin');
        
        //if(Yii::app()->user->isGuest){
		        $this->FB = new Facebook(array(
			  'appId' => $this->devappid,
			  'secret' => $this->devsecret,
			  'cookie' => false, 
			));
	
			$this->Session =  $this->FB->getSession();
	
			$appids = $this->FB->getAppId();  
				if($this->Session) {
				try {
				$uid = $this->FB->getUser();
				$this->user = $this->FB->api('/me');
				} catch (FacebookApiException $e) {
				//print_r($e->getMessage());  exit;
				}
				}
	
				$this->userid = $this->user['id'];
				$this->username = $this->user['email'];	
				$this->fname = $this->user['first_name'];
				$this->lname = $this->user['last_name'];	
	
        		$login = $this->FB->getLoginUrl();
        		$logout = $this->FB->getLogoutUrl();	

        		$url = $this->controller->createAbsoluteUrl('fblogin',array('username'=>$this->user['email'],'fname'=>$this->user['first_name'],'lname'=>$this->user['last_name'],'userid'=>$this->user['id'],'logout'=>CHtml::encode($logout)));
      //     echo $url; exit;
       			$this->user['email'] ? $this->controller->redirect( $url ) : null;
            
        		$this->render('fbview',array('session'=>$this->Session,'user'=>$this->user,'login'=>$login,'logout'=>$logout,'appid'=>$appids));   


        }
              
}